<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="100px" class="teacherForm">

      <el-form-item label="讲师姓名" required>
        <el-tooltip class="item" effect="dark" content="不长于10个字符" placement="top-start">
          <el-input
            ref="nameInput"
            v-model.trim="teacher.name"
            type="text"
            maxlength="10"
            @blur="enableButton"
            @keyup.native="enableButton"/>
        </el-tooltip>
      </el-form-item>

      <el-form-item label="讲师职级">
        <el-select v-model="teacher.level" placeholder="请选择职级">
          <!-- value前面加冒号后，后面双引号里的就是表达式了，而不是字符串 -->
          <el-option :value="1" label="高级讲师"/>
          <el-option :value="2" label="首席讲师"/>
        </el-select>
      </el-form-item>

      <el-form-item label="入驻时间" required>
        <el-col :span="11">
          <el-form-item prop="joinDate">
            <el-date-picker v-model="teacher.joinDate" type="date" placeholder="选择日期" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" :min="0"/>
      </el-form-item>

      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro"/>
      </el-form-item>

      <el-form-item label="讲师资历">
        <!-- 可以设置行数 -->
        <el-input v-model="teacher.career" :rows="5" type="textarea"/>
      </el-form-item>

      <!-- 讲师头像  -->
      <el-form-item label="上传头像">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
          :action="OSS_API+'/admin/oss/file/upload?module=avatar'"
          class="avatar-uploader">
          <img v-if="teacher.avatar" :src="teacher.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="buttonIsDisabled" type="primary" @click="saveOrUpdate('teacher')">确定</el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import teacherApi from '@/api/teacher'

export default {
  data() {
    return {
      // 讲师对象
      teacher: {
        name: '',
        sort: 0,
        level: 1 // 这里的数值1，和上面下拉列表对应，可以设置默认值
      },
      OSS_API: /* process.env.OSS_API */ process.env.BASE_API,
      buttonIsDisabled: true
    }
  },

  mounted() {
    // 自动聚焦
    this.$refs.nameInput.focus()
  },

  created() {
    if (this.$route.params.id) {
      // 根据id查询讲师
      this.fetchDataById(this.$route.params.id)
    }
  },

  methods: {
    enableButton() {
      // console.log('-' + str + '-')
      this.teacher.name = this.teacher.name.replace(/\s+/g, '')
      if (this.teacher.name !== '') {
        this.buttonIsDisabled = false
      } else {
        this.buttonIsDisabled = true
      }
    },

    saveOrUpdate(teacher) {
      // 如果传入的参数中没有id，那就是修改，否则就是新建
      if (!this.teacher.id) {
        this.save(teacher)
      } else {
        this.updateData(teacher)
      }
    },

    save(teacher) {
      teacherApi.save(this.teacher).then((response) => {
      // 弹出成功提示
        this.$message({
          message: response.message,
          type: 'success'
        })
        // 跳转到讲师列表
        this.$router.push({ path: '/teacher' })
      }).catch((err) => {
        if (err === 'cancel') {
          this.$message({
            type: 'info',
            message: '保存失败'
          })
        }
      })
    },

    updateData(teacher) {
      teacherApi.updateById(this.teacher).then((response) => {
        // 弹出成功提示
        this.$message({
          message: response.message,
          type: 'success'
        })
      }).catch((err) => {
        if (err === 'cancel') {
          this.$message({
            type: 'info',
            message: '保存失败'
          })
        }
      })
    },

    reset() {
      /* this.deleteAvatar(this.teacher.avatar) */
      fetch('http://localhost:8120/admin/oss/file/delete?avatarUrl=' + this.teacher.avatar, {
        method: 'DELETE'
      })
      this.teacher = {}
    },

    // 文件上传成功
    handleAvatarSuccess(response) {
      if (response.success) {
        this.teacher.avatar = response.data.url
        // 强制重新渲染，否则不显示图片
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败！')
      }
    },
    // 文件上传失败
    handleAvatarError() {
      this.$message.error('上传失败！(http失败)')
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 根据id查询讲师
    fetchDataById(id) {
      teacherApi.getById(id).then(response => {
        this.teacher = response.data.item
      })
    },
    // 重置后需要从OSS中删除原来上传的图片
    deleteAvatar(avatar) {
      teacherApi.deleteAvatar(avatar)
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
